package com.yiwei.ydd.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yiwei.ydd.R;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.api.bean.MoneyApplyBean;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.event.BankUseEvent;
import com.yiwei.ydd.util.Arith;
import com.yiwei.ydd.util.Dialog;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.Spans;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.UI;
import com.yiwei.ydd.util.Util;
import com.yiwei.ydd.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class WalletWithdrawActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_change_bankcard)
    LinearLayout btnChangeBankcard;
    @BindView(R.id.view_has_bankcard)
    View viewHasBankcard;
    @BindView(R.id.layout_has_bankcard)
    LinearLayout layoutHasBankcard;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.txt_bank_info)
    TextView txtBankInfo;
    @BindView(R.id.edit_money)
    EditText editMoney;
    @BindView(R.id.txt_balance)
    TextView txtBalance;
    @BindView(R.id.txt_fee)
    TextView txtFee;
    @BindView(R.id.txt_true_money)
    TextView txtTrueMoney;
    @BindView(R.id.img_bank_icon)
    ImageView imgBankIcon;

    private Unbinder unbiner;
    private float money_cal;
    private double fee_cal;
    private boolean hasBank;
    private String bankcard_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet_withdraw);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        txtTitle.setText("提现");
        String money = getIntent().getStringExtra("money");
        money_cal = Float.valueOf(money);
        String apply_fee = getIntent().getStringExtra("apply_fee");
        fee_cal = Float.valueOf(apply_fee);
        txtBalance.setText("余额：" + money);

        txtFee.setText(apply_fee + "元");

        editMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(UI.toString(editMoney))) {
                    btnSubmit.setSelected(false);
                    return;
                }

                if (UI.toFloat(editMoney) > money_cal) {
                    editMoney.setText((int) money_cal + "");
                    return;
                }
                txtTrueMoney.setText("￥" + Arith.sub(UI.toFloat(editMoney), fee_cal));
                if (hasBank) {
                    btnSubmit.setSelected(true);
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BankUseEvent event) {
        layoutHasBankcard.setVisibility(View.VISIBLE);
        hasBank = true;
        bankcard_id = event.item.id;
        Glide.with(this).load(event.item.icon).into(imgBankIcon);
        Spanned bank = Spans.with(this).font(event.item.name, getResources().getDimensionPixelSize(R.dimen.x30), 0xff333333).
                font("\n" + event.item.bankcard, getResources().getDimensionPixelSize(R.dimen.x30), 0xff999999).
                build();
        txtBankInfo.setText(bank);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;
    }

    public void getBanksLists() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getBanksLists().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.datas == null || result.datas.size() == 0) {
                        Util.startActivity(this, BankCardFirstActivity.class);
                    } else {
                        Util.startActivity(this, BankListUseActivity.class);
                    }
                });
    }

    public void getMoneyCheck() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getMoneyCheck().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    loadingDialog.dismiss();
                    if (result.datas.is_apply.equals("1")) {
                        Dialog.showDefaultDialog(this, "", "您有一笔在提现记录，请等待平台审核通过，才能发起第二笔提现", "", "知道了", false, new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {
                                finish();
                            }

                            @Override
                            public void cancel() {

                            }
                        });
                    } else {
                        getMoneyApply(bankcard_id, UI.toString(editMoney));
                    }
                });
    }

    public void getMoneyApply(String bankcard_id, String money) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        MoneyApplyBean bean = new MoneyApplyBean();
        bean.bankcard_id = bankcard_id;
        bean.money = money;
        Api.api_service.getMoneyApply(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Dialog.showDefaultDialog(this, "", "您的提现申请已经提交，平台审核通过后，将直接提现到你选择的相关账户。", "", "好", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            finish();
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                });
    }

    @OnClick({R.id.btn_back, R.id.btn_change_bankcard, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_change_bankcard:
                getBanksLists();
                break;
            case R.id.btn_submit:
                if (!hasBank) {
                    ToastUtil.makeText(this, "提现银行卡不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editMoney))) {
                    ToastUtil.makeText(this, "提现金额不能为空");
                    return;
                }

                if (UI.toFloat(editMoney) < 50) {
                    ToastUtil.makeText(this, "余额满50元才能提现");
                    return;
                }
                getMoneyCheck();

                break;
        }
    }
}
